<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;
use App\Models\Airport;
use App\Models\Country;
use Illuminate\Support\Facades\Log;

class PickupCodeController extends Controller
{
    public function index(){
        $status = True;
        return view('pickupcode.index', compact('status'));
    }
    public function submit(Request $request){
        $this->validate($request, [
            'code' => 'required',
            'captcha' => 'required|captcha',
        ],[
            'code.required' => trans('validation.required'),
            'captcha.required' => trans('validation.required'),
            'captcha.captcha' => trans('validation.captcha'),
        ]);
        $code = $request['code'];
        try{
            $result = $this->send_snail_shop($code);
        }catch (\Exception $e){
            Log::error($e);
        }

        if ($result['errorCode'] != 0){
            $status = False;
            return view('pickupcode.index', compact('status', 'code'));
        }

        $goods_name = $result['data']['goods_name'];
        $status = $result['data']['status'];

        if($status == 1){
            $status_msg = '该取货码尚未使用';
        }elseif ($status == 2){
            $status_msg = '该取货码已经使用';
        }elseif ($status == 3){
            $status_msg = '该取货码已经过期';
        }else{
            $status_msg = '该取货码状态未知';
        }
        $country_id = $this->search_country($goods_name);
        if ($country_id){
            session(['country_id' => $country_id]);
        }

        $airports = Airport::all();
        return view('pickupcode.result', compact('airports','goods_name', 'status_msg'));

    }

    protected function send_snail_shop($code){
        $client = new Client([
            'base_uri' => 'http://mall.snail.com/osapi/pickupcode/Pickup_code_info',
            'timeout'  => 2.0,
            'headers' => array('Content-Type'  => 'application/json'),
        ]);

        $res = $client->post('http://mall.snail.com/osapi/pickupcode/Pickup_code_info?code='.$code);

        $result = json_decode($res->getBody(), True);
        Log::info($code);
        Log::info($result);
        return $result;
    }

    protected function search_country($goods_name){
//        通过商品名称判断出是哪个国家的
        $countries = Country::all();
        foreach ($countries as $c){
//            可能strpos找到的字符串位置是0，所以用!==
            if (strpos($goods_name,$c->title) !== false){
                return $c->id;
            }
        }
        return null;
    }

    public function test(Request $request){
//        return $request->session()->get('country_id', 'default');
        return session('country_id');
    }
}
